<?php

class db_file extends singleton
{
	// php singleton wrapper
	static public function &instance() { return parent::instance(__CLASS__); }
	
	protected $root = null;
	protected $storage = array( );
	
	protected function __construct( $root = null )
	{
		$this ->root = $root ? $root : ( root.'.dbfile/' );
	}
	
	public function is_exists( $table )
	{
		if( !is_string( $table ) ) return null;
		foreach( array( 'json', 'serialize' ) as $type )
		{
			$guess = sprintf( '%s%s.%s', $this->root, $table, $type );
			if( file_exists( $guess ) ) return true;
		}
		return false;
	}
	
	public function is_loaded( $table )
	{
		if( !is_string( $table ) ) return null;
		return isset( $this ->storage[ $table ] );
	}
	
	protected function load( $table )
	{
		foreach( array( 'json', 'serialize' ) as $type )
		{
			$guess = sprintf( '%s%s.%s', $this->root, $table, $type );
			if( !file_exists( $guess ) ) continue;

			$data = file_get_contents( $guess );
			$data = ( $type == 'json' )
				? @json_decode( $data, 1 ) : @unserialize( $data );
			if( !$data ) return;

			$this ->storage[ $table ] = $data;
			break;
		}
	}

	static public function contents( $table )
	{
		$db_file = self::instance();

		$file = str_replace('.','/',$table);
		$guess = $db_file->root . $file;

		$guesses = glob( $guess . '.*' );
		if(sizeof($guesses)>1)
			throw new exception( 'Multiple tables exists with name "'.$table.'". Which one you need?' );
		$file = reset($guesses);
		
		if( !file_exists( $file ) ) return;

		return file_get_contents( $file );
	}
	
	protected function get_data( $table )
	{
		if( !$this ->is_Loaded( $table ) )
			$this ->load( $table );
		
		return $this ->storage[$table];
	}
	
	public function get( $table, $id )
	{
		$data = $this ->get_data( $table );
		return isset( $data[$id] )
			? $data[$id]
			: null;
	}
	
	public function get_by( $table, $w = null )
	{
		return $this ->by( $table, $w );
	}

	public function by( $table, $w = null )
	{
		$data = $this ->get_data( $table );

		if( is_null( $w ) )
			return $data;
		
		$result = array( );
		foreach( $data as $id => $row )
			foreach( $w as $k => $v )
			{
				if( !$v || $row[$k] != $v )
					continue;

				$result[$id] = $row;
			}
		
		return $result;
	}

	public function __get( $k )
	{
		return isset($this->k) ? $this->k : null;
	}
}